package com.zjfgz.lib_kt_com.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import java.net.SocketTimeoutException
import kotlin.coroutines.CoroutineContext

open class BaseViewModel : ViewModel(), CoroutineScope {

    private val job by lazy { SupervisorJob() }

    val handler = CoroutineExceptionHandler { _, throwable ->
        when (throwable) {
            is SocketTimeoutException -> onJobError("网络超时")
            else -> onJobError(throwable.message.toString())
        }
    }

    val messageLiveData by lazy { MutableLiveData<String>() }

    val loadingLiveData by lazy { MutableLiveData<Boolean>() }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job + handler

    open fun onJobError(msg: String) {
        messageLiveData.postValue(msg)
        loadingLiveData.postValue(false)
    }
}